package com.ruike.alisurface.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.ruike.alisurface.mqtt.ServiceUtils;
import com.ruike.alisurface.services.MyTopFileImgService;
import com.ruike.alisurface.services.NetWorkListenerService;
import com.ruike.alisurface.services.UvlampTimersService;
import com.ruike.alisurface.ui.answerQuestion.QrCodeActivity;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.ui.mainPage.BindMachineActivity;
import com.ruike.alisurface.ui.mainPage.LoginActivity;
import com.ruike.alisurface.ui.mainPage.VedioAdvActivity;
import com.ruike.alisurface.ui.payPage.PayShowShopActivity;
import com.ruike.alisurface.ui.setting.NetWorkActivity;
import com.ruike.alisurface.ui.setting.SettingActivity;
import com.ruike.alisurface.ui.setting.SlotTestActivity;
import com.ruike.alisurface.ui.setting.StopSellingActivity;
import com.ruike.alisurface.utils.AdvDialogUtils;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.DeviceUtils;
import com.ruike.alisurface.utils.Languages.LanguageUtil;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ThreadUtils;
import com.ruike.alisurface.utils.ZXingUtils;
import com.voodoo.lib_frame.base.BaseActivity;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.voodoo.lib_utils.imageLoader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import static com.ruike.alisurface.utils.ShareKey.BASEUSERID;
import static com.ruike.alisurface.utils.ShareKey.SERVICE_TEL;

/**
 * Author: voodoo
 * CreateDate: 2020-03-25 025 下午 03:01
 * Description: 项目的Activity基类，项目中所有Activity完全继承自该类
 */
public abstract class BaseAty extends BaseActivity implements View.OnClickListener {

    private MyCountDownTimer countDownTimer;
    boolean isReboot = false;

    /**
     * 此方法先于 onCreate()方法执行
     *
     * @param newBase
     */
    @Override
    protected void attachBaseContext(Context newBase) {
        //获取我们存储的语言环境 比如 "en","zh",等等
        String language = ShareUtils.getInstance().getString(ShareKey.LANGUAGE, "");

        /**
         * attach对应语言环境下的context
         */
        super.attachBaseContext(LanguageUtil.attachBaseContext(newBase, language));
    }

    public boolean isFace = true;

    @Override
    protected void onStart() {
        super.onStart();
        isFace = ShareUtils.getInstance().getBoolean(ShareKey.IS_FACE, false);
        if (!EventBus.getDefault().isRegistered(this)) {
//            L.i("注册EventBus", this.getComponentName());
            EventBus.getDefault().register(this);
        }
        boolean isuvLampService = ShareUtils.getInstance().getBoolean("isuvLampService", false);
        if (/*this instanceof PayForQRCodeActivity ||*/ this instanceof PayShowShopActivity ||
                /*this instanceof SelectPayTypeActivity ||*/ this instanceof SlotTestActivity) {
            if (isuvLampService && ServiceUtils.isServiceRunning(this, UvlampTimersService.class.getName())) {
                L.e("紫外灯=", " 检测到MUvlampTimersService      停止紫外灯流程");
                ServiceUtils.stopService(this, UvlampTimersService.class);
            }
        } else {
            if (isuvLampService && !ServiceUtils.isServiceRunning(this, UvlampTimersService.class.getName())) {
                L.e("紫外灯=", " 检测到MUvlampTimersService      开启紫外灯流程");
                ServiceUtils.startService(this, UvlampTimersService.class);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        L.i("当前页面==" + this.getLocalClassName());
    }

    public static int signalStrength;
    int mCountLog = 0;//根据次数进行日志记录

    @Override
    protected void onResume() {
        super.onResume();
        /**
         *处理信号的回调及UI更新
         */
        NetWorkListenerService.setPhoneWaftListener(new NetWorkListenerService.PhoneWaftListener() {
            @Override
            public void onStrengthsChanged(String type, int signalStrength, int level) {

                if (!isNetConnect()) {
                    level = 0;
                }
                if (mCountLog++ >= 30) {
                    mCountLog = 0;
                    L.i("mqtt  开启信号检测服务 信号 级别==" + type + "是否有网络连接" + isNetConnect() + "==" + level + "==" + signalStrength);
                }
                EventBus.getDefault().post(new MsgEventBus("网络信号强度", level + ""));
                if (waft_lay != null) {
                    waft_lay.setVisibility(View.VISIBLE);
                }
                if (title_waft_content == null && title_waft_img == null) {
                    return;
                }

                if ("TYPE_ETHERNET".equals(type)) {
                    title_waft_img.setImageResource(R.drawable.icon_wangxian);
                    title_waft_content.setText("网线");
                    return;
                }
                if (level == 1) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_1);
                    title_waft_content.setText("信号弱");
                } else if (level == 2) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_2);
                    title_waft_content.setText("信号微弱");
                } else if (level == 3) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_3);
                    title_waft_content.setText("信号中");
                } else if (level == 4) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_4);
                    title_waft_content.setText("信号强");
                } else if (level == 5) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_4);
                    title_waft_content.setText("未知强度");
                } else if (level == 0) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_0);
                    title_waft_content.setText("无信号");
                }
                if (level == 0) {
                    isReboot = true;
                } else {
                    if (isNetConnect()) {
                        isReboot = false;
                        ThreadUtils.removeCallbacks(RebootUi);
                        if (dialog != null && dialog.isShowing()) {
                            dialog.cancel();

                            L.i("mqtt  有信号了 取消弹窗 及计时线程");
                        }
                    }
                }
            }
        });
    }

    CustomDialog dialog;
    int restCount;

    /**
     * 提示无网络开始倒数计时重启
     *
     * @param tip
     */
    public void goRebootTip(String tip) {
        boolean isStop = ShareUtils.getInstance().getBoolean(ShareKey.IS_NETWORK_STATUS, false); // 停止售卖

        if (this instanceof StopSellingActivity || isStop) {
            ThreadUtils.removeCallbacks(RebootUi);
            L.i("已经在停止售卖页了");
            return;
        }
        boolean isNet = ShareUtils.getInstance().getBoolean(ShareKey.IS_NETWORK_STATUS, false); // 网络异常页
        if (this instanceof NetWorkActivity || isNet) {
            ThreadUtils.removeCallbacks(RebootUi);
            L.i("已经在网络异常页了");
            return;
        }

        if (dialog != null && dialog.isShowing()) {

        } else {
            restCount = ShareUtils.getInstance().getInt(ShareKey.IS_OFFLINE_RESTART_APPCOUNT, 10);
            if (restCount <= 0) {
                ShareUtils.getInstance().putBoolean(ShareKey.IS_NETWORK_STATUS, true); // 网络异常页
                startActivity(NetWorkActivity.class, null);
                finish();
                return;
            }
            dialog = new CustomDialog.Builder(BaseAty.this).setTitle("温馨提示")
                    .setMessage(tip).setTouchOutsideCloseDialog(true).create();
            dialog.show();
            ThreadUtils.postUIDelayed(RebootUi, 60000);
        }
    }

    Runnable RebootUi = new Runnable() {
        @Override
        public void run() {
            if (isReboot) {
                --restCount;
                ShareUtils.getInstance().putInt(ShareKey.IS_OFFLINE_RESTART_APPCOUNT, restCount);
                setNoRestMachine();
            }
        }
    };

    /**
     * 重启机器
     */
    public void setNoRestMachine() {
        //重启板子
        String cmd = "su -c reboot";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            L.i("onClick: ===" + process.waitFor());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    ImageView title_waft_img;
    TextView title_waft_content;
    RelativeLayout waft_lay;
    TextView snTv;
    public RelativeLayout titleBar_root_rlayout;

    @SuppressLint("ClickableViewAccessibility")
    public void initTitleBar(boolean isRightClickToSetting) {
        L.i("信号 initTitleBar", this.getComponentName());
        titleBar_root_rlayout = findViewById(R.id.titleBar_root_rlayout);
        boolean isimg_adv = ShareUtils.getInstance().getBoolean(ShareKey.GET_RK_AD, false);
        titleBar_root_rlayout.setBackgroundResource(isimg_adv ? R.color.colorTitleBar_red : R.color.colorTitleBar);
        ImageView titleBar_qrcode_imgv = findViewById(R.id.titleBar_qrcode_imgv);
        TextView appVersionTv = findViewById(R.id.titleBar_appVersion_tv);
        ImageView titleBar_titleIco_imgv = findViewById(R.id.titleBar_titleIco_imgv);
        waft_lay = findViewById(R.id.waft_lay);
        title_waft_img = findViewById(R.id.title_waft_img);
        title_waft_content = findViewById(R.id.title_waft_content);

//        if (Constant.isNoTtitle) {
//            titleBar_titleIco_imgv.setVisibility(View.GONE);
//        } else {
//            titleBar_titleIco_imgv.setVisibility(View.VISIBLE);
//        }
//        String logo = ShareUtils.getInstance().getString(ShareKey.LOGO, "");
//        if (logo != null && !TextUtils.isEmpty(logo)) {
//            GlideImageLoader.loadImage(this, logo, titleBar_titleIco_imgv);
//        }
        appVersionTv.setText(BuildConfig.VERSION_NAME);
        snTv = findViewById(R.id.titleBar_sn_tv);
        snTv.setText(new StringBuffer().append(getString(R.string.afterMarketPhoneStr)).append("：").append(ShareUtils.getInstance().getString(ShareKey.SERVICE_TEL, getString(R.string.noPhoneStr))));

        setDataSNcode(titleBar_qrcode_imgv);

        if (isRightClickToSetting) {
            findViewById(R.id.titleBar_setting_view).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    continuousClick();
                }
            });
        }
    }

    /**
     * 设置二维码
     *
     * @param codeimg
     */
    public void setDataSNcode(ImageView codeimg) {
        HashMap<String, String> map = new HashMap<>();
        map.put("version", "Android");
        map.put("sn", DeviceUtils.getDeviceSn());
        String jsonSN = GsonUtils.MapToJson(map);
        File SnFile = new File(Constant.pathCode);
        if (!SnFile.exists()) {
            L.i("查询二维码不存在");
            Bitmap SnBitmap = ZXingUtils.getInstance().createQRImage(jsonSN, 300, 300, BitmapFactory.decodeResource(getResources(), 0));
            ZXingUtils.getInstance().saveFile(Constant.pathCode, SnBitmap);
        }
        ImageLoader.loadImage(BaseAty.this, Constant.pathCode, codeimg);
    }

    /**
     * @param path    下载保存地址
     * @param picList 图片集合地址
     */
    public void startTopAdvFileService(String path, ArrayList<String> picList) {
        Intent intent = new Intent(this, MyTopFileImgService.class);
        intent.putStringArrayListExtra("topadv", picList);
        intent.putExtra("filepath", path);
        startService(intent);
    }

    /**
     * 开始倒计时
     *
     * @param time    倒计时时间，单位：秒
     * @param showTv  展示倒计时的TextView
     * @param jumpAty 倒计时结束时跳转的界面
     */
    public void startCountdownTimer(int time, final TextView showTv, Class jumpAty) {
        CountdownTimercancal();
        L.i("开始倒计时==time=" + time);
        countDownTimer = new MyCountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long l) { // 展示倒计时
                if (showTv != null) {
                    int time = (int) (l / 1000) + 1;
                    if (time < 20) {
                        showTv.setTextColor(getResources().getColor(R.color.colorCountdownTimeRed));
                    }
                    L.v("开始倒计时=" + (int) (l / 1000) + 1);
                    showTv.setText(new StringBuffer(String.valueOf(time)).append("s"));
                }
            }

            @Override
            public void onFinish() {
                L.i("结束倒计时");
                /*if (BaseAty.this instanceof PayForQRCodeActivity) {
                    EventBus.getDefault().post(new MsgEventBus("计时结束", "查询订单倒计时结束"));
                }*/
//                FActivityManager.getInstance().killOtherActivity();
                String baseUserid = ShareUtils.getInstance().getString(BASEUSERID, "RK_test");
                if (baseUserid.equals("RK_test")) {
                    startActivity(BindMachineActivity.class, null);
                    finish();
                    return;
                }
                if (ShareUtils.getInstance().getBoolean(ShareKey.IS_STOP_SELLING, false)) {
                    startActivity(StopSellingActivity.class, null); // 停止售卖
                } else {
                    if (jumpAty != null) {
                        if (jumpAty.getName().contains("MainActivity")) {
                            BackMainUtils.setActivity(BaseAty.this);
                        } else {
                            // 倒计时结束之后直接跳转指定的界面
                            startActivity(jumpAty, null);
                        }
                    } else {
                        //网络异常页的是否跳转
                        boolean net_sp = ShareUtils.getInstance().getBoolean(ShareKey.IS_NETWORK_STATUS, false); // 网络异常页
                        if (net_sp) {
                            startActivity(NetWorkActivity.class, null);
                            return;
                        }
                        // 跳到广告或者是主界面
                        int advType = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE);
                        switch (advType) {
                            // 0和1是广告界面，跳转过去之后广告界面内部有图片或者视频广告的判断
                            case 0:
                            case 1:
                                startActivity(VedioAdvActivity.class, null);
                                break;
                            default: // 2或者是其他值则判定为无广告，直接停留在扫码界面
                                startActivity(QrCodeActivity.class, null);
                                break;
                        }
                    }
                }
                finish();
            }
        }.start();
    }


    protected void CountdownTimercancal() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    final static int COUNTS = 5;// 点击次数
    final static long DURATION = 2000;// 规定有效时间
    long[] mHits = new long[COUNTS];

    // 多次连续点击
    protected void continuousClick() {
        // 每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        // 为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            mHits = new long[COUNTS]; // 重新初始化数组

            String baseUserid = ShareUtils.getInstance().getString(BASEUSERID, "RK_test");

            if (baseUserid.equals("RK_test") || BuildConfig.DEBUG) {
                startActivity(SettingActivity.class, null);
            } else {
                startActivity(LoginActivity.class, null);
            }
            finish();
        }
    }

    @Override
    public void onNetChange(int enetMobil, boolean isConnect) {
        if (!isConnect && ShareUtils.getInstance().getBoolean(ShareKey.IS_OFFLINE_RESTART_APP)) {
//            showErrorTip(getResources().getString(R.string.networkDisconnectAndRestartAppStr));
            if (NetWorkListenerService.mPhoneWaftListener != null) {
                NetWorkListenerService.mPhoneWaftListener.onStrengthsChanged("TYPE_MOBILE", signalStrength, 0);
                L.i("机器无网络了，一分钟会自动重启");
                removeProgressDialog();
                goRebootTip("机器无网络了，一分钟会自动重启");
                // 断网重启APP
            }
        } else if (!isConnect) {
            showToast(getResources().getString(R.string.networkDisconnectStr));
            if (NetWorkListenerService.mPhoneWaftListener != null) {
                NetWorkListenerService.mPhoneWaftListener.onStrengthsChanged("TYPE_MOBILE", signalStrength, 0);
            }
        } else {
            isReboot = false;
            if (dialog != null && dialog.isShowing()) {
                L.i("机器有网络了，取消弹窗");
                dialog.cancel();
            }
            ThreadUtils.removeCallbacks(RebootUi);
        }
    }


    /**
     * EventBus 回调
     *
     * @param event
     */
    public abstract void doEventBusResult(MsgEventBus event);

    // 当一个Message Event提交的时候这个方法会被调用
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusResult(MsgEventBus event) {
        //   L.i("onMessageEvent： ", event.toString());
        doEventBusResults(event);
        doEventBusResult(event);
    }

    /**
     * EventBus 回调
     *
     * @param event
     */
    public void doEventBusResults(MsgEventBus event) {
        if (snTv != null && event.getType().equals(SERVICE_TEL)) {
            snTv.setText(new StringBuffer().append(getString(R.string.afterMarketPhoneStr)).append("：").
                    append(ShareUtils.getInstance().getString(ShareKey.SERVICE_TEL, getString(R.string.noPhoneStr))));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        AdvDialogUtils.dlCancal();

    }

    @Override
    protected void onStop() {
        super.onStop();
        CountdownTimercancal();
        if (EventBus.getDefault().isRegistered(this)) {
//            L.i("EventBus，解除绑定", this.getComponentName());
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.i("销毁：" + this.getLocalClassName());
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
            dialog = null;
        }
        if (tip_dialog != null && tip_dialog.isShowing()) {
            tip_dialog.cancel();
            tip_dialog = null;
        }
    }

    public boolean isAccounts = false; //结算
    public Timer tip_timer;//计时

    /**
     * 支付类型的判断 及发送能否通信的指令即返回值操作
     * 跳转到不同的页面
     */
    public void IntentActivity() {
        // 通过发送灯光指令判断是否能够通讯
        Ttys3Utils.getInstance().LEDSetting(10, "0", "2", "1", 70, 15);
        if (tip_timer == null) {
            tip_timer = new Timer();
        }
        L.i("通信计时1====开始");
        tip_timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new MsgEventBus("没有指令返回", ""));
                        L.i("通信计时2====结束");
                        alt();
                    }
                });
            }
        }, 3000);

    }

    public void cencalTiptimer() {
        if (tip_timer != null) {
            tip_timer.purge();
            tip_timer.cancel();
            tip_timer = null;
        }
    }

    CustomDialog tip_dialog;

    /**
     * 通讯异常提示框
     */
    private void alt() {
        try {
            if (tip_dialog != null && tip_dialog.isShowing()) {
                tip_dialog.dismiss();
            }
            tip_dialog = new CustomDialog.Builder(this)
                    .setTitle("温馨提示").setMessage("底层通信出现异常，暂时停止购买，请稍后重试!!!")
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                        }
                    })
                    .setTouchOutsideCloseDialog(false).create();
            tip_dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            EventBus.getDefault().post(new MsgEventBus("Uvlamp", "无触摸了"));
        } else {
            EventBus.getDefault().post(new MsgEventBus("Uvlamp", "有触摸了"));
        }
        return super.dispatchTouchEvent(ev);
    }
}
